package cn.o.app.ui.pull;

import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ScrollView;

@SuppressWarnings("deprecation")
public class PullPolicy {

	public boolean canPullDown(View v) {
		if (v instanceof AdapterView<?>) {
			return canPullDown((AdapterView<?>) v);
		}
		if (v instanceof ScrollView) {
			return canPullDown((ScrollView) v);
		}
		if (v instanceof WebView) {
			return canPullDown((WebView) v);
		}
		return true;
	}

	public boolean canPullUp(View v) {
		if (v instanceof AdapterView<?>) {
			return canPullUp((AdapterView<?>) v);
		}
		if (v instanceof ScrollView) {
			return canPullUp((ScrollView) v);
		}
		if (v instanceof WebView) {
			return canPullUp((WebView) v);
		}
		return true;
	}

	protected boolean canPullDown(AdapterView<?> v) {
		if (v.getCount() == 0) {
			// 没有item的时候也可以下拉刷新
			return true;
		} else if (v.getFirstVisiblePosition() == 0
				&& v.getChildAt(0).getTop() >= 0) {
			// 滑到顶部了
			return true;
		} else
			return false;
	}

	protected boolean canPullUp(AdapterView<?> v) {
		if (v.getCount() == 0) {
			// 没有item的时候也可以上拉加载
			return true;
		} else if (v.getLastVisiblePosition() == (v.getCount() - 1)) {
			// 滑到底部了
			if (v.getChildAt(v.getLastVisiblePosition()
					- v.getFirstVisiblePosition()) != null
					&& v.getChildAt(
							v.getLastVisiblePosition()
									- v.getFirstVisiblePosition()).getBottom() <= v
							.getMeasuredHeight())
				return true;
		}
		return false;
	}

	protected boolean canPullDown(ScrollView v) {
		if (v.getScrollY() == 0)
			return true;
		else
			return false;
	}

	protected boolean canPullUp(ScrollView v) {
		if (v.getScrollY() >= (v.getChildAt(0).getHeight() - v
				.getMeasuredHeight()))
			return true;
		else
			return false;
	}

	protected boolean canPullDown(WebView v) {
		if (v.getScrollY() == 0)
			return true;
		else
			return false;
	}

	protected boolean canPullUp(WebView v) {
		if (v.getScrollY() >= Math.floor(v.getContentHeight() * v.getScale()
				- v.getMeasuredHeight()))
			return true;
		else
			return false;
	}

}
